using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text.RegularExpressions;
using BL;
using BE;

public partial class PerfilAdmin : BasePage
{
    #region Atributos
    private Boolean LoadDataEmpty = false;
    #endregion

    #region Eventos
    protected void Page_Load(object sender, EventArgs e)
    {        
        txtNombre.Focus();

        if (!IsPostBack)
        {
            SetLabels();
            CargarPerfiles();
        }
    }
    protected void btnSalir_Click(object sender, EventArgs e)
    {
        Response.Redirect("Default.aspx");
    }
    protected void btnAgregar_Click(object sender, EventArgs e)
    {
        try
        {
            EnableEditItemLink(false);

            gvPerfil.FooterRow.Visible = true;
            btnAgregar.Enabled = false;
        }
        catch (ManagerBusinessException)
        {
            ShowErrorMessageInAjax(UpdatePanelPerfil);
        }
        catch (Exception ex)
        {
            Publish(ex, String.Empty);
            ShowErrorMessageInAjax(UpdatePanelPerfil);
        }
    }
    protected void btnEliminar_Click(object sender, EventArgs e)
    {
        try
        {
            ArrayList arrayDelete = GetItemsCheckedInGrid();
            if (arrayDelete.Count > 0)
            {
                String strPerfilNombre = String.Empty;
                for (int i = 0; i < arrayDelete.Count; i++)
                {
                    Object[] args = (Object[])arrayDelete[i];
                    long uidPerfil = Convert.ToInt64(args[0].ToString());
                    Int32 intResult = PerfilBO.EliminarPerfil(uidPerfil);
                    if (intResult == -1)
                    {
                        strPerfilNombre += args[1].ToString() + ",";
                    }
                }
                CargarPerfiles();

                if (strPerfilNombre != String.Empty)
                {
                    strPerfilNombre = strPerfilNombre.Substring(0, strPerfilNombre.LastIndexOf(","));
                    String strMessage = String.Format(Resources.Resource.msg_EliminarPerfil, strPerfilNombre);
                    ScriptManager.RegisterStartupScript(UpdatePanelPerfil, GetType(), "Script", "alert('" + strMessage + "');", true);
                    return;
                }
            }
        }
        catch (ManagerBusinessException)
        {
            ShowErrorMessageInAjax(UpdatePanelPerfil);
        }
        catch (Exception ex)
        {
            Publish(ex, String.Empty);
            ShowErrorMessageInAjax(UpdatePanelPerfil);
        }
    }
    protected void gvPerfil_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        try
        {
            GridView grid = (GridView)sender;
            grid.EditIndex = -1;

            CargarPerfiles();
            btnAgregar.Enabled = true;
        }
        catch (ManagerBusinessException)
        {
            ShowErrorMessageInAjax(UpdatePanelPerfil);
        }
        catch (Exception ex)
        {
            Publish(ex, String.Empty);
            ShowErrorMessageInAjax(UpdatePanelPerfil);
        }
    }
    protected void gvPerfil_RowDataBound(object sender, GridViewRowEventArgs e)
    {        
        if (e.Row.RowType == DataControlRowType.Header)
        {
            ((Label)e.Row.FindControl("lblNombre")).Text = Resources.Resource.gvPerfil_lblNombre;
            ((Label)e.Row.FindControl("lblDescripcion")).Text = Resources.Resource.gvPerfil_lblDescripcion;            
        }        
    }
    protected void gvPerfil_RowEditing(object sender, GridViewEditEventArgs e)
    {
        GridView grid = (GridView)sender;
        grid.EditIndex = e.NewEditIndex;

        btnAgregar.Enabled = false;

        CargarPerfiles();
    }
    protected void gvPerfil_RowCommand(object sender, GridViewCommandEventArgs e)
    {        
        long uidPerfilId = 0;
        String strNombre = String.Empty;
        String strDescripcion = String.Empty;        
        String strPattern = String.Empty;
        
        try
        {
            GridView grid = (GridView)sender;

            switch (e.CommandName)
            {
                case "Update":
                case "AddItem":

                    if (e.CommandName == "AddItem")
                    {
                        uidPerfilId = 0;
                        strNombre = ((TextBox)grid.FooterRow.FindControl("txtNombreAdd")).Text;
                        strDescripcion = ((TextBox)grid.FooterRow.FindControl("txtDescripcionAdd")).Text;                        
                    }
                    else
                    {
                        GridViewRow row = grid.Rows[grid.EditIndex];
                        uidPerfilId = Convert.ToInt64(((Label)row.FindControl("lblPerfilId")).Text);
                        strNombre = ((TextBox)row.FindControl("txtNombre")).Text;
                        strDescripcion = ((TextBox)row.FindControl("txtDescripcion")).Text; 
                    }

                    String strMessage = String.Empty;

                    if (strNombre == String.Empty)
                        strMessage = Resources.Resource.msg_PerfilNombreValido;
                    if (strDescripcion == String.Empty)
                        strMessage += Resources.Resource.msg_PerfilDescripcionValido;

                    if (!CommonBO.ValidarNombre(uidPerfilId,0,strNombre, "Perfil"))
                        strMessage += String.Format(Resources.Resource.msg_ValidarNombre, "nombre");
                   
                    if (strMessage != String.Empty)
                    {                        
                        ScriptManager.RegisterStartupScript(UpdatePanelPerfil, GetType(), "Script", "alert('" + strMessage + "');", true);
                        return;
                    }

                    Perfil oPerfil = new Perfil();
                    oPerfil.PerfilId = uidPerfilId;
                    oPerfil.Nombres = strNombre;
                    oPerfil.Descripcion = strDescripcion;
                    oPerfil.LogUsuarioId = ((Usuario)Session[Constans.SessionUsuario.ToString()]).UsuarioId;

                    PerfilBO.InsertarPerfil(oPerfil);

                    grid.EditIndex = -1;

                    CargarPerfiles();
                    btnAgregar.Enabled = true;
                    //grid.FooterRow.Visible = false;
                    EnableEditItemLink(true);

                    break;
                case "CancelItem":
                    ((TextBox)grid.FooterRow.FindControl("txtNombreAdd")).Text = String.Empty;
                    ((TextBox)grid.FooterRow.FindControl("txtDescripcionAdd")).Text = String.Empty;                    

                    btnAgregar.Enabled = true;
                    //grid.FooterRow.Visible = false;
                    EnableEditItemLink(true);
                    break;
            }
        }
        catch (ManagerBusinessException)
        {
            ShowErrorMessageInAjax(UpdatePanelPerfil);
        }
        catch (Exception ex)
        {
            Publish(ex, String.Empty);
            ShowErrorMessageInAjax(UpdatePanelPerfil);
        }
    }
    protected void gvPerfil_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {

    }
    protected void gvPerfil_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        gvPerfil.PageIndex = e.NewPageIndex;
        CargarPerfiles();
    }
    protected void gvPerfil_RowCreated(object sender, GridViewRowEventArgs e)
    {
        if (LoadDataEmpty && e.Row.RowType == DataControlRowType.DataRow)
        {
            e.Row.Visible = false;
            e.Row.Controls.Clear();
        }
    }
    protected void gvPerfil_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        GridViewRow row = gvPerfil.Rows[e.RowIndex];
        long uidPerfilId = Convert.ToInt64(((Label)row.FindControl("lblPerfilId")).Text);
        String strPerfilNombre = ((Label)row.FindControl("lblPerfilNombre")).Text;
        Int32 intResult = PerfilBO.EliminarPerfil(uidPerfilId);
        if (intResult == -1)
        {
            String strMessage = String.Format(Resources.Resource.msg_EliminarPerfil, strPerfilNombre);
            ScriptManager.RegisterStartupScript(UpdatePanelPerfil, GetType(), "Script", "alert('" + strMessage + "');", true);
            return;
        }
        else
        {
            CargarPerfiles();
        }
    }
    protected void btnBuscar_Click(object sender, EventArgs e)
    {
        CargarPerfiles();
    }
    #endregion

    #region Metodos
    protected void SetLabels()
    {
        btnAgregar.Text = Resources.Resource.btnAgregar;
        btnEliminar.Text = Resources.Resource.btnEliminar;
        lblTituloPerfil.Text = Resources.Resource.lblTituloPerfil;        
    }

    private void CargarPerfiles()
    {
        try
        {
            DataTable dtPerfiles = PerfilBO.ObtenerPerfiles(txtNombre.Text.Trim());

            if (dtPerfiles.Rows.Count == 0)
            {
                dtPerfiles.Rows.Add(dtPerfiles.NewRow());
                LoadDataEmpty = true;
            }
            
            gvPerfil.DataSource = dtPerfiles;
            gvPerfil.DataBind();
        }
        catch (ManagerBusinessException)
        {
            ShowErrorMessageInAjax(UpdatePanelPerfil);
        }
        catch (Exception ex)
        {
            Publish(ex, String.Empty);
            ShowErrorMessageInAjax(UpdatePanelPerfil);
        }
    }

    public void EnableEditItemLink(bool blnValue)
    {
        for (int i = 0; i < gvPerfil.Rows.Count; i++)
        {
            if (((LinkButton)gvPerfil.Rows[i].FindControl("lnkEdit")) != null)
                ((LinkButton)gvPerfil.Rows[i].FindControl("lnkEdit")).Enabled = blnValue;
        }
    }
    private ArrayList GetItemsCheckedInGrid()
    {
        ArrayList arrayList = new ArrayList();
        for (int i = gvPerfil.Rows.Count - 1; i >= 0; i--)
        {
            GridViewRow dgRow = gvPerfil.Rows[i];
            if (dgRow.RowType == DataControlRowType.DataRow)
            {
                if (((CheckBox)dgRow.FindControl("chk")).Checked)
                {
                    arrayList.Add(new Object[] { ((Label)dgRow.FindControl("lblPerfilId")).Text, ((Label)dgRow.FindControl("lblPerfilNombre")).Text });
                }
            }
        }
        return arrayList;
    }
    #endregion       
}
